<template>
  <el-upload
    ref="upload"
    v-loading="uploading"
    class="img-upload"
    element-loading-text="上传中，请耐心等待"
    :action="uploadUrl"
    accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.PNG,.BMP"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :before-remove="beforeRemove"
    :on-progress="handleProgress"
    :on-success="handleSuccess"
    multiple
    :limit="1"
    :on-exceed="handleExceed"
    :file-list="fileList"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传单个jpg/png文件，且不超过1MB{{ extraTip }}</div>
  </el-upload>
</template>

<script>
const uploadApi = process.env.VUE_APP_IMG_UPLOAD_API
export default {
  name: 'ImgUploadSingle',
  props: ['extraTip'],
  data() {
    return {
      fileList: [],
      url: '',
      uploading: false,
      uploadUrl: uploadApi
    }
  },
  methods: {
    handleRemove(file, fileList) {
      this.url = ''
      this.$emit('onRemove')
    },
    handlePreview(file) {
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择1个文件，本次选择了${files.length}个文件，共选择了${files.length + fileList.length}个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除${file.name}？`)
    },
    handleSuccess(response) {
      this.uploading = false
      if (response.code == 0) {
        this.url = response.data
        this.$emit('onUpload')
        this.$message.success(`上传成功！`)
      } else {
        this.fileList = []
        this.$message.warning(`上传失败！`)
      }
    },
    handleProgress() {
      this.uploading = true
    },
    clear() {
      this.url = ''
      this.$refs.upload.clearFiles()
    }

  }
}
</script>

<style scoped>

</style>
